<script setup lang="ts">
    import { ref, computed, watch, onMounted, reactive } from 'vue';
    import { showToast } from 'vant';
    import { useOrderInfo } from '@/store/modules/evaluate'
    import API_ORDER from '@/apis/order';
    import { useI18n } from 'vue-i18n';
    const { t } = useI18n();
    // 组件属性
    const props = defineProps({
        show: {
            type: Boolean,
            default: false,
        },

    });
    let appOrder = useOrderInfo()
    const emit = defineEmits(['closeLan', 'update:show']);
    let evaPrams = reactive({
        id: '',
        comments: []
    })
    let appData = reactive({})
    // 响应式状态
    const isMobile = ref(false);
    const localShow = ref(props.show);
    const rating = ref(0);
    const comment = ref('');
    const fileList = ref < Array < any >> ([]);

    // 监听父组件传入的 show 变化
    watch(
        () => props.show,
        (newVal) => {
            localShow.value = newVal;
            if (newVal) {
                appData = appOrder.getEvaluate
                evaPrams['id'] = appData.id
                appData?.items.forEach(e => {
                    let obj = {
                        item_id: e.id,
                        level: 5,
                        content: '',
                        images: [],
                        fileList: []
                    }
                    evaPrams.comments.push(obj)
                });
                console.log(evaPrams, '评分项');
            }
        }
    );

    // 检测设备函数
    const checkDevice = () => {
        isMobile.value = window.innerWidth <= 768;
    };

    // 评分对应的文本
    const ratingText = computed(() => {
        if (rating.value === 0) return '请评分';
        if (rating.value <= 1) return '非常差';
        if (rating.value <= 2) return '较差';
        if (rating.value <= 3) return '一般';
        if (rating.value <= 4) return '良好';
        return '非常满意';
    });

    // 关闭弹窗
    const closePopup = () => {
        emit('closeLan');
        setTimeout(() => {
            resetForm();
        }, 200);
    };

    const closeIcon = () => {
        emit('closeLan');
        setTimeout(() => {
            resetForm();
        }, 500);
    };
    const closeMask = () => {
        emit('closeLan');
        setTimeout(() => {
            resetForm();
        }, 500);
    };

    // 打开弹窗
    const openPop = () => {
        // 可以在这里添加初始化逻辑
    };

    // 重置表单
    const resetForm = () => {
        evaPrams.comments = []
        evaPrams.id = ''
        fileList.value = [];
    };

    // 提交评价
    const submitReview = async () => {
        try {
            // 1. 遍历所有评论项，收集所有图片上传的 Promise
            const allUploadPromises = evaPrams.comments.map(async (item, index) => {
                if (!item.fileList || item.fileList.length === 0) {
                    // 如果没有图片，直接返回空数组
                    item.images = [];
                    return;
                }

                // 上传当前评论项的所有图片
                const urls = await Promise.all(
                    item.fileList.map(async (e) => {
                        const formData = new FormData();
                        formData.append('file', e.file);
                        const res = await API_ORDER.commonUpload(formData);
                        return res.data.url;
                    })
                );
                // 将上传后的 URLs 存入当前评论项
                evaPrams.comments[index].images = urls
            });

            // 2. 等待所有评论项的图片上传完成
            await Promise.all(allUploadPromises);

            console.log(evaPrams, '所有图片上传完成后的数据');
            setTimeout(async () => {
                // 3. 提交评价
                const result = await API_ORDER.orderComment(evaPrams);
                if (result.code === 1) {
                    showToast({
                        message: res.data.msg,
                        icon: 'passed',
                    });

                    setTimeout(() => {
                        resetForm();
                        emit('closeLan');
                    }, 1500);
                }
            }, 200);

        } catch (err) {

        }
    };
    // 上传后读取数据
    let handleAfterRead = async (file, index) => {
        console.log(file, index, '上传文件');
        // let formData = new FormData()
        // formData.append('file', file.file)
        // let res = await API_ORDER.commonUpload(formData)
        // if (res.code == 1) {
        //     evaPrams.comments[index].images.push(res.data.url)
        // }
    }
    // 删除图片
    let uploadDelete = (data, index) => {

    }
    onMounted(() => {
        // 初始化设备检测
        window.addEventListener('resize', checkDevice);
        checkDevice();
    })
</script>
<template>
    <div>
        <van-popup v-model:show="localShow" round :position="isMobile ? 'bottom' : 'right'" :style="
        isMobile
          ? { height: '90%', width: '100%' }
          : { width: '30%', height: '100%' }
      " @click-close-icon="closeIcon" @opened="openPop" @click-overlay="closeMask">
            <div class="evaluate-container">
                <!-- 头部 -->
                <div class="evaluate-header">
                    <div class="evaluate-title">{{t('home.LeaveReview')}}</div>
                    <div class="close-icon" @click="closePopup">✕</div>
                </div>
                <!-- 内容区域 -->
                <div class="evaluate-body" v-if="evaPrams.comments.length>0">
                    <div v-for="(i,index) in appData?.items">
                        <!-- 标题 -->
                        <div class="section">
                            <!-- <div class="section-title">
                            <van-icon name="star" />
                            商品
                        </div> -->
                            <div>
                                <div class="f14">{{ i.goods_title }}</div>
                            </div>
                        </div>
                        <!-- 评分区域 -->
                        <div class="section">
                            <div class="section-title">
                                <van-icon name="star" />
                                {{t('home.score')}}
                            </div>
                            <div class="rate-container">
                                <van-rate v-model="evaPrams.comments[index].level" allow-half :size="isMobile ? 24 : 32"
                                    color="#ffd21e" void-icon="star" void-color="#eee" />
                                <!-- <div class="rate-text">{{ ratingText }}</div> -->
                            </div>
                        </div>

                        <!-- 评价内容 -->
                        <div class="section">
                            <div class="section-title">
                                <van-icon name="comment" />
                                {{t('home.EvaluationContent')}}
                            </div>
                            <van-field v-model="evaPrams.comments[index].content" rows="5" autosize type="textarea"
                                maxlength="300" placeholder="..." show-word-limit class="comment-field" />
                        </div>

                        <!-- 图片上传 -->
                        <div class="section">
                            <div class="section-title">
                                <van-icon name="photo" />
                                {{t('home.UploadPhotos')}}
                            </div>
                            <van-uploader v-model="evaPrams.comments[index].fileList" :max-count="9" multiple
                                :preview-size="isMobile ? 55 : 75" :deletable="true" :upload-text="t('home.addPhoto')"
                                :after-read="(file) => handleAfterRead(file, index)"
                                @delete=" (file) => uploadDelete(file, index)" :preview-options="{ closeable: true }">
                                <template #preview-delete>
                                    <div><van-icon name="cross"
                                            style="background-color: #000;color:#fff;padding: 2px" /></div>
                                </template>
                            </van-uploader>
                        </div>
                        <van-divider :style="{ borderColor: '#666' }" />
                    </div>
                </div>
                <!-- 底部提交按钮 -->
                <div class="evaluate-footer">
                    <van-button type="primary" block round size="large" @click="submitReview" class="submit-button">
                        <van-icon name="passed" />
                        {{t('home.SubmitReview')}}
                    </van-button>
                </div>
            </div>
        </van-popup>
    </div>
</template>

<style lang="less" scoped>
    @import './index.less';
</style>